//
// Created by ting on 2019-09-17.
//

#include <jni.h>
#include <string>
#include "tools.h"

jbyteArray getJByteArray(JNIEnv *env, const char *src) {
    jsize length = static_cast<jsize>(strlen(src));
    jbyteArray byteArray = env->NewByteArray(length);
    jbyte *srcBytes = (jbyte *) src;
    env->SetByteArrayRegion(byteArray, 0, length, srcBytes);
    return byteArray;
}


jstring getJString(JNIEnv *env, const char *src) {
    jclass stringClazz = env->FindClass("java/lang/String");
    jmethodID methodID = env->GetMethodID(stringClazz, "<init>", "([BLjava/lang/String;)V");
    jstring encoding = env->NewStringUTF("utf-8");

    jsize length = static_cast<jsize>(strlen(src));
    jbyteArray bytes = env->NewByteArray(length);
    env->SetByteArrayRegion(bytes, 0, length, (jbyte *) src);
    jstring resultString = (jstring) env->NewObject(stringClazz, methodID, bytes, encoding);

    env->DeleteLocalRef(stringClazz);
    env->DeleteLocalRef(encoding);
    env->DeleteLocalRef(bytes);

    return resultString;
}

//jstring to uint8_t*
uint8_t* jstringTostring(JNIEnv* env, jstring jstr)
{
    uint8_t* rtn = NULL;
    jclass clsstring = env->FindClass("java/lang/String");
    jstring strencode = env->NewStringUTF("utf-8");
    jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B");
    jbyteArray barr= (jbyteArray)env->CallObjectMethod(jstr, mid, strencode);
    jsize alen = env->GetArrayLength(barr);
    jbyte* ba = env->GetByteArrayElements(barr, JNI_FALSE);
    if (alen > 0)
    {
        rtn = (uint8_t*)malloc(alen + 1);
        memcpy(rtn, ba, alen);
        rtn[alen] = 0;
    }
    env->ReleaseByteArrayElements(barr, ba, 0);
    return rtn;
}

//uint8_t* to jstring
jstring stoJstring(JNIEnv* env, const uint8_t* pat)
{
    jclass strClass = env->FindClass("java/lang/String");
    jmethodID ctorID = env->GetMethodID(strClass, "<init>", "([BLjava/lang/String;)V");
    jbyteArray bytes = env->NewByteArray(strlen((char*)pat));
    env->SetByteArrayRegion(bytes, 0, strlen((char*)pat), (jbyte*)pat);
    jstring encoding = env->NewStringUTF("utf-8");
    return (jstring)env->NewObject(strClass, ctorID, bytes, encoding);
}